/* OLD STUFF
 * package template;
 

import org.apache.wicket.markup.html.WebPage;

**
 * Page that adds a template border for layout.
 * 
 *
public class EditEvent extends WebPage
{
    **
     * Constructor
     *
    public EditEvent()
    {
    	add(new PageLayout("calendarBorder"));
        
    }
}
*/

package template;

import java.awt.List;
import java.lang.reflect.Array;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;

import net.java.ao.DatabaseProvider;
import net.java.ao.EntityManager;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.hsqldb.User;

/**
 * Page that adds a template border for layout.
 * 
 */
public class EditEvent extends Restricted
{
	//declaration of instance variables
	private String inputNameMessage = "";
	private String startDateInput = "";
	private String startTimeInput = "";
	private String endDateInput = "";
	private String endTimeInput = "";
	private String inputDescriptionMessage = "";
	private int selectedStartMonth;
	private int daysInStartMonth;
	private int daysInEndMonth;
	private int selectedEndMonth;
	private String selectedEvent;
	private String selectedCalendar;
	private Calendar calendar;
	private HashMap<String, Integer> map;
	
    /**
     * Constructor
     */
	
	//nested private class of form for onSubmit override
	private class CreateEventForm extends Form {
		private EditEvent _editEvent;
		public CreateEventForm(String id, EditEvent editEvent) {
			super(id);
			_editEvent = editEvent;
		}
		public void onSubmit() {
			try {
				_editEvent.editEvent();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	//constructor
    public EditEvent()
    {
    	//hashmap linking events to their IDs
    	map = new HashMap<String, Integer>();
    	
    	//propertymodel's for the different input fields
    	PropertyModel inputNameModel = new PropertyModel(this, "inputNameMessage");
    	PropertyModel startDateModel = new PropertyModel(this, "startDateInput");
    	PropertyModel startTimeModel = new PropertyModel(this, "startTimeInput");
    	PropertyModel endDateModel = new PropertyModel(this, "endDateInput");
    	PropertyModel endTimeModel = new PropertyModel(this, "endTimeInput");
    	PropertyModel inputDescriptionModel = new PropertyModel(this, "inputDescriptionMessage");
    	
    	//instantiating the form
    	CreateEventForm form = new CreateEventForm("form", this);
    	
    	//adding the propertymodel's to the form
    	form.add(new TextArea("inputDescriptionArea", inputDescriptionModel));
    	form.add(new TextField("inputNameField", inputNameModel));
    	form.add(new TextField("startDate", startDateModel));
    	form.add(new TextField("startTime", startTimeModel));
    	form.add(new TextField("endDate", endDateModel));
    	form.add(new TextField("endTime", endTimeModel));
    	
    	//getting instance of entitymanager
    	EntityManager manager = new EntityManager(DatabaseProvider.getInstance(
				"jdbc:hsqldb:mem:basic-ao", null, null));
    	
    	//linked list of calendar and event names for editing values
    	LinkedList<String> calendarNames = new LinkedList<String>();
    	LinkedList<String> eventNames = new LinkedList<String>();
    	
    	//defining the user of the current session
    	Person user = (Person)_session.getUser();
    	Calendar[] userCalendars;
    	
    	//list of the events belonging to the user
    	LinkedList<Event> userEvents = new LinkedList<Event>();
		try {
			
			//retrieves all calendars belonging to the user
			userCalendars = manager.find(Calendar.class, "creatorID = ?", user.getID());
			
			//loads events from every user's calendar except for Viewable Events
			//event names and calendar names are stored in the lists for dropdown menus
	    	for(int i=2;i<userCalendars.length;i++) {
	    		calendarNames.add(i-2, userCalendars[i].getName());
	    		Event[] calendarEvents = userCalendars[i].getEvents();
	    		for(int j=0;j<calendarEvents.length;j++)
	    			userEvents.add(calendarEvents[j]);
	    	}
	    	
	    	//iterator to traverse list of event names
	    	Iterator<Event> iterator = userEvents.iterator();
	    	
	    	//loading of events into map linked with their IDs
	    	while(iterator.hasNext()) {
	    		Event tempEvent = iterator.next();
	    		map.put(tempEvent.getName(), tempEvent.getID());
	    		eventNames.add(tempEvent.getName());
	    		
	    	} 
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//property models for selected calendar/event, these are added to the form
		PropertyModel eventModel = new PropertyModel(this,"selectedEvent");
		form.add(new DropDownChoice("selectedEvent", eventModel, eventNames));
		PropertyModel calendarModel = new PropertyModel(this, "selectedCalendar");
		form.add(new DropDownChoice("selectedCalendar", calendarModel, calendarNames));
		
		//form is added to the layout
    	_layout.add(form);
    }
    public void editEvent() throws SQLException {
    	
    	//entitymanager instance
    	EntityManager manager = new EntityManager(DatabaseProvider.getInstance(
				"jdbc:hsqldb:mem:basic-ao", null, null));
    	
    	//define user of current session
    	Person user = (Person)_session.getUser();
    	
    	//manager retrieves the selected event from database
    	Event event = manager.get(Event.class, map.get(selectedEvent));
    	
    	//definition of relation variable
    	EventsToCalendars relation = null;
    	
    	//retrieving the relation that exists between current calendar and event being edited
    	Calendar[] userCalendars = manager.find(Calendar.class, "creatorID = ?", user.getID());
    	for(int i=0;i<userCalendars.length;i++) {
    		EventsToCalendars[] relations = manager.find(EventsToCalendars.class, "calendarID = ? AND eventID = ?", userCalendars[i].getID(), event.getID());
    		if(relations.length > 0)
    			relation = relations[0];
    	}
    	
    	//definition of current calendar variable
    	Calendar currCalendar = relation.getCalendar();
    	
    	//any fields that arent entered are loaded with the values already set on
    	//the event
    	if(inputNameMessage == null)
    		inputNameMessage = event.getName();
    	if(startDateInput == null) {
    		Date tempStart = event.getStartDate();
    		startDateInput = (tempStart.getMonth()+1)+"/"+tempStart.getDate()+"/"+(tempStart.getYear()+1900);
    	}
    	if(startTimeInput == null) {
    		Date tempStart = event.getStartDate();
    		startTimeInput = tempStart.getHours()+":"+tempStart.getMinutes();
    	}
    	if(endDateInput == null) {
    		Date tempEnd = event.getEndDate();
    		endDateInput = (tempEnd.getMonth()+1)+"/"+tempEnd.getDate()+"/"+(tempEnd.getYear()+1900);
    	}
    	if(endTimeInput == null) {
    		Date tempEnd = event.getEndDate();
    		endTimeInput = tempEnd.getHours()+":"+tempEnd.getMinutes();
    	}
    	if(inputDescriptionMessage == null)
    		inputDescriptionMessage = event.getDescription();
    	
    	Calendar[] calendar = new Calendar[1];
    	
    	//if the no calendar is selected, change it to be the current calendar
    	//otherwise, find the selected calendar in database
    	if(selectedCalendar == null)
    		calendar[0] = currCalendar;
    	else
    		calendar = manager.find(Calendar.class, "creatorID = ? AND name = ?", user.getID(), selectedCalendar);
    	
    	//values are loaded into variables to use to set new values on event
    	Date startDate = new Date(startDateInput+","+startTimeInput+":");
    	Date endDate = new Date(endDateInput+","+endTimeInput+":");
    	String name = inputNameMessage;
    	String description = inputDescriptionMessage;
    	
    	//check to see if the end date is before the start date
    	//if so, redirect user to error page displaying this
    	if(endDate.compareTo(startDate) < 0) {
    		this.setResponsePage(EditEventEndDateError.class);
    		return;
    	}
    	
    	//retrieve events belonging to the calendar that the event will be placed on
    	Event[] calendarEvents = calendar[0].getEvents();
    	
    	//determine if the name of the event already exists on that calendar
    	//if so, redirect to error page
    	for(int i=0;i<calendarEvents.length;i++) {
    		String tempName = calendarEvents[i].getName();
    		if(name.equalsIgnoreCase(tempName)) {
    			this.setResponsePage(EditEventError.class);
    			return;
    		}
    	}
		
		//update the values of various event fields
    	event.setName(name);
    	event.setDescription(description);
    	event.setStartDate(startDate);
    	event.setEndDate(endDate);
    	event.save();
    	
    	//update the relation to link to the new calendar
    	relation.setCalendar(calendar[0]);
    	relation.setEvent(event);
    	relation.save();
    	
    	//redirect to View Calendars page
    	this.setResponsePage(ViewCalendars.class);
    }
}